package my.cloud.study.controller;

import my.cloud.study.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class MyDemoController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    private String serviceUrl(){
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("eureka-provider1");
        if(serviceInstanceList == null || serviceInstanceList.isEmpty()){
            return null;
        }
        return serviceInstanceList.get(0).getUri().toString();
    }

    @GetMapping("usr")
    public User user(){
//        String serviceUrl = serviceUrl();
        return this.restTemplate.getForObject(getUserServiceUrl(),User.class);
    }

    private String getUserServiceUrl(){
        return "http://eureka-provider/usr";
    }
}
